package com.gdut.simple.view.activity.user;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.gdut.simple.R;
import com.gdut.simple.common.BitmapUtils;
import com.gdut.simple.common.LogUtils;
import com.gdut.simple.contract.UpdateProfileContract;
import com.gdut.simple.data.entity.User;
import com.gdut.simple.event.RxBus;
import com.gdut.simple.event.UserEvent;
import com.gdut.simple.presenter.user.UpdateProfilePresenter;
import com.gdut.simple.view.basic.AbsBasicActivity;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.functions.Action1;

public class UpdateProfileActivity extends AbsBasicActivity implements UpdateProfileContract.View {

    private static final String TAG = UpdateProfileActivity.class.getSimpleName();

    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;

    @BindView(R.id.id_follow_user_profile)
    CircleImageView mUserProfile;

    @OnClick(R.id.id_capture_image)
    void capture() {
        captureImage();
    }

    @OnClick(R.id.id_photo_album)
    void album() {
        callGallery();
    }

    private UpdateProfileContract.Presenter mPresenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_update_profile);
        ButterKnife.bind(this);
        initToolbar();
        new UpdateProfilePresenter(this);
        setConfig();
        mSubscription = RxBus.getDefault().toObservable(UserEvent.class).subscribe(new Action1<UserEvent>() {
            @Override
            public void call(UserEvent event) {
                LogUtils.d(TAG, "receive UserEvent");
                setConfig();
            }
        });
    }

    private void initToolbar() {
        mToolbar.setTitle(R.string.set_profile);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }


    private void setConfig() {
        User user = BmobUser.getCurrentUser(User.class);
        if (user == null || user.getObjectId() == null) {
            return;
        }
        if (user.getProfile() != null) {
            Picasso.with(this)
                    .load(user.getProfile().getUrl())
                    .error(R.drawable.ic_load_error)
                    .into(mUserProfile);
        }
    }

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;  //调用照相机
    private static final int CALL_GALLERY_REQUEST_CODE = 2;  //调用图库
    private static final int CROP_PICTURE = 3; //裁剪
    private static final int IMAGE_WIDTH = 300;  //图片输出大小
    private static final int IMAGE_HEIGHT = 300;  //图片输出大小
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 100;

    private String mImagePath = Environment.getExternalStorageDirectory() + "/temp.jpg";
    private File mImageFile = new File(mImagePath);
    private Uri mImageUri;

    /**
     * 调用系统图库
     */
    private void callGallery() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, CALL_GALLERY_REQUEST_CODE);
    }

    /**
     * 调用系统照相机
     */
    private void captureImage() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    CAMERA_PERMISSION_REQUEST_CODE);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            mImageUri = Uri.fromFile(mImageFile);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mImageUri = FileProvider.getUriForFile(this, "com.gdut.simple", mImageFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    }

    /**
     * 裁剪
     */
    private void cropImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", IMAGE_WIDTH);
        intent.putExtra("outputY", IMAGE_HEIGHT);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        startActivityForResult(intent, CROP_PICTURE);
    }

    /**
     * 拍照和系统图库选择图片返回事件处理
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:  //拍照结果回调,进行裁剪
                    cropImage(mImageUri);
                    break;

                case CALL_GALLERY_REQUEST_CODE:  //系统图库回调
                    if (data != null) {
                        cropImage(data.getData());
                    }
                    break;

                case CROP_PICTURE:  //裁剪回调
                    updateProfile(data);
                    break;
            }
        } else {
            LogUtils.e("result code is " + resultCode);
        }
    }

    /**
     * 动态权限申请回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CAMERA_PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    mImageUri = Uri.fromFile(mImageFile);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        mImageUri = FileProvider.getUriForFile(this, "com.gdut.simple", mImageFile);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                }
                break;
        }
    }

    private void updateProfile(Intent data) {
        if (data != null) {
            Bitmap bitmap = data.getParcelableExtra("data");
            BitmapUtils.saveBitmap2File(bitmap, mImagePath);
            mPresenter.update();
        } else {
            LogUtils.e("data get url is null");
        }
    }

    @Override
    public String getImagePath() {
        return mImagePath;
    }

    @Override
    public void next() {
        RxBus.getDefault().post(new UserEvent(true));
    }

    @Override
    public void setPresenter(@NonNull UpdateProfileContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

}
